--
-- Author: shineflag
-- Date: 2016-09-22 10:19:53
--
local json = json or require("dkjson")

--协议文本
local protos = {
	--注册
	signup = {
		req = {
			userid = "",
		},
		resp = {
			ret = 0,
		}
	},
	--登录
	signin = {
		req = {
			userid = "",
		},
		resp = {
			ret = 0,
		}
	},

	ping = {
		req = {
			t = 0,
		},
		resp = {
			t = 0,
		}
	},

		--登录
	login = {
		req = {
			userid = "",
		},
		resp = {
			ret = 0,
		}
	},

	alloc = {
		req = {
			level = 1,  --int 场次
			oldroomid = 1010001,  --不希望加入的roomid
			tagroomid = 1010001,  --期望的roomid
		},

		resp = {

		},
	}

	roomlogin = {
		req = {
			roomid = 1010001, --int  房间id
			mid   =  1,  --int 用户id
			nick  =  "",  --string 名称 
			showinfo = "{}"  --string 需要展示的其它信息
		},
		resp = {
			roomid = 1010001,  --int  房间id
			mid = 1,            --int 用户id
			money = 10000,  --int64 金币
	    }
	}

	roomsit = {
		req = {
			roomid = 1010001,
			seatid = 1,
			coin = 10000,
		},

		resp = {
			ret = 0,
		}
	}

	guess_bet = {
		req = {
			bet = 1,  --1、石头 > 2、剪刀 > 3、布 > 1、石头
		}，

		resp = {
			ret = 0,  --0--成功  1--未登录房间 2--状态错误
		}
	}

	guess_result = {
		resp = {
			winid = "alice",
		}

	}

}

local function pack(data)
    return json.encode(data)
end

local function unpack(msg)
	local info = json.decode(msg)
	return info
end



--创建一个请求的包
local function create_req(cmd,args)

	local p = protos[cmd]
	if p then
		local data = {}
		data.cmd = cmd 
		if p.req then
			local req = {}
			for key,value in pairs(p.req) do
				if args[key] then
					req[key] = args[key]
				else
					req[key] = value
				end
			end

			data.req = req
		end

		return pack(data)
	end

	return nil 

end

--根据参数创建一个回复包
local function create_resp(cmd,args)

	local p = protos[cmd]
	if p then
		local data = {}
		data.cmd = cmd 
		if p.resp then
			local resp = {}
			for key,value in pairs(p.resp) do 
				if args[key] then
					resp[key] = args[key]
				else
					resp[key] = value
				end
			end

			data.resp = resp
		end

		return pack(data)
	end

	return nil 

end

local proto = {}
proto.create_req = create_req
proto.create_resp = create_resp
proto.unpack = unpack

return proto 